package com.atguigu.daijia.rules.service.impl;

import com.atguigu.daijia.model.form.rules.FeeRuleRequest;
import com.atguigu.daijia.model.form.rules.FeeRuleRequestForm;
import com.atguigu.daijia.model.vo.rules.FeeRuleResponse;
import com.atguigu.daijia.model.vo.rules.FeeRuleResponseVo;
import com.atguigu.daijia.rules.mapper.FeeRuleMapper;
import com.atguigu.daijia.rules.service.FeeRuleService;
import lombok.extern.slf4j.Slf4j;
import org.joda.time.DateTime;
import org.kie.api.runtime.KieContainer;
import org.kie.api.runtime.KieSession;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Slf4j
@Service
@SuppressWarnings({"unchecked", "rawtypes"})
public class FeeRuleServiceImpl implements FeeRuleService {

    //规则引擎对象
    @Autowired
    private KieContainer kieContainer;


    /*
     * 计算订单费用
     * */
    @Override
    public FeeRuleResponseVo calculateOrderFee(FeeRuleRequestForm feeRuleRequestForm) {
        //封装输入对象
        FeeRuleRequest feeRuleRequest = new FeeRuleRequest();
        feeRuleRequest.setDistance(feeRuleRequestForm.getDistance());//代驾里程
        //将代驾时间转化成string类型
        Date startTime = feeRuleRequestForm.getStartTime();
        String startime = new DateTime(startTime).toString("HH:mm:ss");
        feeRuleRequest.setStartTime(startime);//代驾时间
        feeRuleRequest.setWaitMinute(feeRuleRequestForm.getWaitMinute());//等待时间
        //drools规则引擎实现
        KieSession kieSession = kieContainer.newKieSession();
        //封装返回对象
        FeeRuleResponse feeRuleResponse = new FeeRuleResponse();
        kieSession.setGlobal("feeRuleResponse",feeRuleResponse);//封装drools全局变量
        kieSession.insert(feeRuleResponse);//传入对象
        kieSession.fireAllRules();//触发规则
        kieSession.dispose();//关闭引擎
        //引擎计算完毕，此时feeRuleResponse应该有内容
        FeeRuleResponseVo feeRuleResponseVo = new FeeRuleResponseVo();
        //feeRuleResponse -》 feeRuleResponseVo
        BeanUtils.copyProperties(feeRuleResponse,feeRuleResponseVo);//对象拷贝，封装返回值
        //封装数据到vo并返回
        return feeRuleResponseVo;
    }
}
